package app.server.project.main.service.db.dao.user;


import app.server.project.main.service.db.entity.user.UserTaskEntity;
import app.server.project.main.service.db.mapper.user.UserTaskMapper;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class UserTaskDao extends ServiceImpl<UserTaskMapper, UserTaskEntity> {

    @Cacheable(key = "#userId", cacheNames = "app.server.project.main.service.db.dao.UserTaskDao")
    public List<UserTaskEntity> getAll(long userId) {
        var data = this.list(Wrappers.<UserTaskEntity>lambdaQuery().eq(UserTaskEntity::getUserId, userId));
        data.forEach(v -> {
            v.setSynDb(true);
        });
        return data;
    }

    public UserTaskEntity getOne(List<UserTaskEntity> list, int taskId, long userId) {
        UserTaskEntity userRaceEntity = null;
        var val = list.stream().filter(v -> v.getTaskId() == taskId).findAny();
        if (val.isPresent()) return val.get();
        userRaceEntity = UserTaskEntity.of(IdUtil.getSnowflakeNextId(), taskId, userId);
        list.add(userRaceEntity);
        return userRaceEntity;
    }

}
